import render_helper from "./render_helper.mjs";
import thin_render from "./thin_render.mjs";
import render_content from "./render_content.mjs";
import datarover from "./datarover.mjs";
import { nearest_data } from "./nearest.mjs";

export default function object_template(container, template) {
  let d;
  if (typeof template.data === "function") {
    d = template.data({ container, template, data: nearest_data(container) });
  } else if (template.data !== undefined) {
    d = template.data;
  } else if (template.datapath !== undefined) {
    d = datarover(container, template.datapath);
  }

  if (Array.isArray(d)) {
    // console.log(d);
    d.forEach((data, i) => {
      // console.log({ data, i });
      render(data, i);
    });
  } else {
    render(d);
  }

  function render(data, rowindex) {
    if (!template.hasOwnProperty("when")) {
      do_render();
    } else if (typeof template.when === "function") {
      if (
        template.when({
          container: container,
          template: template,
          data: data || nearest_data(container),
        })
      )
        do_render();
    } else if (template.when) do_render();

    function do_render() {
      let element_name = Object.keys(template)[0];
      let element = document.createElement(element_name);
      container.appendChild(element);

      if (data !== undefined) {
        element.thin_data = data;
        if (rowindex) element.thin_rowindex = rowindex;
      }

      render_helper(element, template);

      // 一些后续处理
      switch (element_name) {
        case "fieldset":
          // fieldset添加title
          if (template.title) {
            let legend = document.createElement("legend");
            legend.innerText = template.title;
            element.appendChild(legend);
          }
          break;
        case "textarea":
          element.name = template.textarea;
          break;
        // case "input":
        //   element.name = template.input;
        //   break;
        case "a":
          if (template.href)
            element.setAttribute(
              "href",
              render_content(element, template.href)
            );
          break;
        default:
          break;
      }
      thin_render(element, template[element_name]);
    }
  }
}
